package org.garden.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 忽略空值配置 ObjectMapper om = get(); om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
 * om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 */
public class JacksonUtil {

    private static ObjectMapper get() {
        return new ObjectMapper();
    }

    public static String string(Object object) throws Exception {
        if (object == null) {
            return null;
        }
        return get().writeValueAsString(object);
    }

    public static <T> T read(String str, Class<T> t) throws Exception {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        return get().readValue(str, t);
    }

    public static Map entityToMap(Object object) throws Exception {
        if (object == null) {
            return new HashMap<>();
        }
        return get().convertValue(object, Map.class);
    }

    public static <T> T mapToEntity(Map<String, Object> map, Class<T> clazz) throws Exception {
        if (map == null || map.isEmpty()) {
            return null;
        }
        return get().readValue(string(map), clazz);
    }
}
